let express = require('express')
let Router = express.Router()
let {
    create,
    verify
} = require('./token')
let mongo = require('../../db/mongo.js')
const token = require('./token')
let ObjectId = require('mongodb').ObjectId;
let upload = require('./multer')
let config = require('../../config.json')

/*
    用户管理相关接口：
        * 验证用户名是否存在 get
        * 注册 post
        * 登录 get 7天免登录
        * 验证 token
        * 查询列表 get
        * 删除用户 delete
        * 修改密码 put
        * 上传头像
        /user/...
        */

//    * 验证用户名是否存在 get
Router.get('/checkname', async (req, res) => {
    let data = {}
    try {
        let p = await mongo.find({
            colname: "user",
            query: req.query
        })
        if (p.length) {
            data = {
                code: 3000,
                flag: false,
                message: '账号已存在'
            }
        } else {
            data = {
                code: 2000,
                flag: true,
                message: '账号不存在'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// * 注册 post 
//name:<string>  password:<number>
Router.post('/reg', async (req, res) => {
    let data = {}
    try {
        let arr = []
        arr.push(req.body)
        let p = await mongo.insert({
            colname: 'user',
            data: arr
        })
        console.log(p);
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '注册成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '注册失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// * 上传头像
Router.post('/headpic', upload.single("avatar"), async (req, res) => {
    //中间件upload.single('请求中包含上传文件的属性')已完成文件的上传,只剩下改写服务端文件的路径
    let data = {}
    let str = req.file.path.replace(/\\/, '/') //处理前端发送来的文件的路径
    let url = config.URL + str //拼接成服务器的路径
    let {
        id
    } = req.body
    id = ObjectId(id)
    try {
        let p = await mongo.update({
            colname: 'user',
            query: {
                _id: id
            },
            data: {
                pic: url
            }
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '上传成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '上传失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// * 登录 get 7天免登录
Router.get('/login', async (req, res) => {
    let data = {}
    try {
        let {
            name,
            password,
            vcode
        } = req.query;
        if(vcode!==req.session.vcode){
            data={
                code: 1000,
                flag: false,
                message: '验证失败'
            }
            res.send(data)
            return
        }
        let p = await mongo.find({
            colname: "user",
            query: {
                name,
                password
            }
        })
        if (p.length) {
            data = {
                code: 2000,
                flag: true,
                message: '登录成功',
                token: create(password)
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '登录失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})
//token校验
Router.get('/verify', (req, res) => {
    let data = {}
    let {
        token
    } = req.query;
    let p = verify(token)
    if (p) {
        data = {
            code: 2000,
            flag: true,
            message: '校验通过',
        }
    } else {
        data = {
            code: 3000,
            flag: false,
            message: '校验失败'
        }
    }
    res.send(data)
})

// * 查询列表 get
Router.get('/getlist', async (req, res) => {
    let data = {}
    let {
        query,
        page,
        pageSize,
        sort
    } = req.query //结构出的都是字符
    if (query) {
        query = JSON.parse(query) //把前端发来的请求数据从字符类型转为对象类型
    }
    if (sort) {
        sort = JSON.parse(sort)
    }

    try {
        let p = await mongo.find({
            colname: "user",
            query, //接收对象类型参数
            page: page * 1,
            pageSize: pageSize * 1,
            sort
        })
        let total = await mongo.findAll({
            colname: "user",
            query
        })
        if (p.length) {
            data = {
                code: 2000,
                flag: true,
                message: '查询成功',
                page, //当前第几页
                pageSize, //一页有多少数据
                total: total.length, //数据总数
                pages: Math.ceil(total.length / pageSize), //多少页数据
                datalist: p //数据
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '数据为空'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// 模糊搜索，返回匹配的列表
Router.get('/search', async (req, res) => {
    let {
        name,
        sex
    } = req.query
    // 正则表达式，用变量定义，每次执行时，都根据传的变量得到 正则表达式，
    // 用正则表达式对库进行筛选
    let reg
    if(name){
         reg = new RegExp(name, "ig") // 全局匹配，不区分大小写
    }
    try {
        let total = await mongo.findAll({
            colname: "user"
        })
        console.log(reg);
        if(name){
            total = total.filter(item => item.name.search(reg) >= 0)
        }
        total.forEach(item => {
            item.password = "不能看"
        })
        if(sex){
            total=total.filter(item=>item.sex==sex)
        }
        if (total.length) {
            data = {
                code: 2000,
                flag: true,
                message: '查询成功',
                total: total.length, //数据总数
                datalist: total //数据
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

//通过_id查找用户
Router.get('/getuser/:id', async (req, res) => {
    let data
    try {
        let id = ObjectId(req.params.id)
        let p = await mongo.find({
            colname: "user",
            query: {
                _id: id
            }
        })
        if (p.length) {
            data = {
                code: 2000,
                flag: true,
                message: '查询成功',
                total: p.length, //数据总数
                datalist: p //数据
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '数据为空'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)

})


// 新增用户
Router.post('/adduser', upload.single("avatar"), async (req, res) => {
    console.log(req.files); //存图片
    console.log(req.body); //其他部分数据
    // res.send("数据上传")
    let data = {}
    let str
    let url
    if (req.file) {
        str = req.file.path.replace(/\\/, '/') //处理前端发送来的文件的路径
        url = config.URL + str //拼接成服务器的路径
    }
    goodinf = {
        pic: url,
        ...req.body
    }
    try {
        let newarr = []
        newarr.push(goodinf)
        let p = await mongo.insert({
            colname: "user",
            data: newarr
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '添加用户成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '添加用户失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// 编辑用户
Router.put('/reset/:id', upload.single("avatar"), async (req, res) => {
    let data = {}
    let str
    let url
    if (req.file) {
        str = req.file.path.replace(/\\/, '/') //处理前端发送来的文件的路径
        url = config.URL + str //拼接成服务器的路径
    }
    try {
        id = ObjectId(req.params.id)
        let p = await mongo.update({
            colname: "user",
            query: {
                _id: id
            },
            data: {
                pic: url,
                ...req.body
            }
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '修改成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '修改失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

//删除头像
Router.put('/delpic/:id', async (req, res) => {
    let data = {}
    try {
        id = ObjectId(req.params.id)
        let p = await mongo.update({
            colname: "user",
            query: {
                _id: id
            },
            data: {
                pic: ""
            }
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '删除成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '删除失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// * 删除用户 delete
Router.delete('/remove/:id', async (req, res) => {
    let data = {}
    try {
        let id = ObjectId(req.params.id);

        //    console.log(req.params);
        //    console.log(typeof req.params);
        let p = await mongo.remove({
            colname: "user",
            query: {
                "_id": id
            }
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '删除成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '删除失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})

// * 修改密码 put
Router.put('/reset', async (req, res) => {
    let data = {}
    try {
        let {
            id,
            password
        } = req.body;
        id = ObjectId(req.body.id);
        //    console.log(typeof req.body,req.body);
        let p = await mongo.update({
            colname: "user",
            query: {
                _id: id
            },
            data: {
                password
            }
        })
        if (p.flag) {
            data = {
                code: 2000,
                flag: true,
                message: '修改成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '修改失败'
            }
        }
    } catch (err) {
        console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器异常'
        }
    }
    res.send(data)
})



module.exports = Router